<template>
  <div>
    <el-form :inline="true" v-show="isSearchCollapse" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
    </el-form>
    <el-row>
      <el-button v-if="hasPermission('basicdata:basictree:partDeviceNode:addLevelOne')" type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button>
      <el-button-group class="pull-right">
          <el-button
            type="default"
            size="small"
            icon="el-icon-refresh"
            @click="refreshList">
          </el-button>
      </el-button-group>
    </el-row>
    <el-table
        :data="dataList"
        ref="treeTable"
        style="width: 100%"
        row-key="id"
        border
        v-loading="loading"
        :indent="32"
        lazy
        :load="loadNode"
        @expand-change="expandChange"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
        <el-table-column
            prop="code"
            show-overflow-tooltip
            min-width="300px"
            header-align="left"
            fixed
            label="设备编码及名称">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false"  @click="view(scope.row.id)">
               <span v-if="scope.row.code !== undefined">{{'[' + scope.row.code + ']' + scope.row.name}}</span>
               <span v-if="scope.row.code === undefined">{{'[' + ']' + scope.row.name}}</span>
              </el-link>
            </template>
          </el-table-column>
        <el-table-column
            prop="level"
            show-overflow-tooltip
            :formatter="function(row, column, cellValue, index) {
              let typeNames = ['厂区', '产线', '设备', '部件', '零件']
              if (row.level <= typeNames.length) {
                return '第' + row.level + '级 ['+ typeNames[row.level - 1] +']'
              }
              return '第' + row.level + '级'
            }"
            label="设备层级"
            >
          </el-table-column>
        <el-table-column
            prop="runState"
            show-overflow-tooltip
            label="运行状态"
            v-model="searchForm.runState">
          <template slot-scope="scope" >
              <i class="el-icon-warning" v-if= " scope.row.runState !== undefined && scope.row.runState === '0' " style="color:red;" ></i>
              <i class="el-icon-success" v-if= " scope.row.runState !== undefined && scope.row.runState === '1' " style="color:lightgreen;"></i>
              {{ $dictUtils.getDictLabel("basicdata_part_device_node_running_state", scope.row.runState, '-') }}
          </template>
          </el-table-column>
        <el-table-column
            prop="isShow"
            show-overflow-tooltip
            label="是否显示">
            <template slot-scope="scope">
              <el-tag type="success" v-if= "scope.row.isShow === '1'">
                 {{ $dictUtils.getDictLabel("yes_no", scope.row.isShow, '-') }}
              </el-tag>
              <el-tag type="danger" v-if= "scope.row.isShow === '0'">
                 {{ $dictUtils.getDictLabel("yes_no", scope.row.isShow, '-') }}
              </el-tag>
              <el-tag v-if= "scope.row.isShow === '-'">
                 {{ $dictUtils.getDictLabel("yes_no", scope.row.isShow, '-') }}
              </el-tag>
            </template>
          </el-table-column>
        <el-table-column
            prop="grade"
            show-overflow-tooltip
            label="设备级别">
            <template slot-scope="scope" >
              <span type="success" v-if= "scope.row.isIot === '0' && ( scope.row.grade ==='A' || scope.row.grade ==='B' || scope.row.grade ==='C' || scope.row.grade ==='D') ">
                {{ scope.row.grade }}
              </span>
              <span type="success" v-if= "scope.row.isIot === '0' && scope.row.grade ==='1'">
                A
              </span>
              <span type="success" v-if= "scope.row.isIot === '0' && scope.row.grade ==='2'">
                B
              </span>
              <span type="success" v-if= "scope.row.isIot === '0' && scope.row.grade ==='3'">
                C
              </span>
              <span type="success" v-if= "scope.row.isIot === '0' && scope.row.grade ==='4'">
                D
              </span>
              <span type="success" v-if= "scope.row.isIot === '1'">
                 {{ $dictUtils.getDictLabel("basicdata_part_device_node_grade", scope.row.grade, '') }}
              </span>
            </template>
          </el-table-column>
        <el-table-column
            prop="isIot"
            show-overflow-tooltip
            label="是否是物联设备">
            <template slot-scope="scope">
              <el-tag type="success" v-if= "scope.row.isIot === '1'">
                 {{ $dictUtils.getDictLabel("yes_no", scope.row.isIot, '-') }}
              </el-tag>
              <el-tag type="danger" v-if= "scope.row.isIot === '2'">
                 {{ $dictUtils.getDictLabel("yes_no", scope.row.isIot, '-') }}
              </el-tag>
            </template>
          </el-table-column>
        <el-table-column
            prop="remarks"
            show-overflow-tooltip
            label="备注信息">
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            fixed="right"
            width="400"
            label="操作">
            <template  slot-scope="scope">
              <el-button v-if="hasPermission('basicdata:basictree:partDeviceNode:view')" type="text" size="small" icon="el-icon-view" @click="view(scope.row.id)">查看</el-button>
              <el-button v-if="hasPermission('basicdata:basictree:partDeviceNode:edit')" type="text" size="small" icon="el-icon-edit" @click="edit(scope.row.id, scope.row)">修改</el-button>
              <el-button v-if="hasPermission('basicdata:basictree:partDeviceNode:del')" type="text" size="small" icon="el-icon-delete" @click="del(scope.row.id, scope.row)">删除</el-button>
              <el-button v-if="hasPermission('basicdata:basictree:partDeviceNode:add')"  type="text" size="small" icon="el-icon-circle-plus-outline" @click="addChild(scope.row.id, scope.row.name, scope.row.level, scope.row.code, scope.row)">添加下级节点</el-button>
            </template>
          </el-table-column>
      </el-table>
        <!-- 弹窗, 新增 / 修改 -->
    <PartDeviceNodeForm  ref="partDeviceNodeForm" :row="currentRow" @refreshCurrentNode="refreshCurrentNode" @refreshDataList="refreshList"></PartDeviceNodeForm>
  </div>
</template>

<script>
  import PartDeviceNodeForm from './PartDeviceNodeForm'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  export default {
    data () {
      return {
        dataList: [],
        searchForm: {
          runState: '',
          code: '',
          level: '',
          type: '',
          purpose: '',
          lifeCycle: '',
          comsumeQuota: '',
          duty: '',
          isShow: '',
          grade: '',
          isIot: '',
          remarks: ''
        },
        reSolve: '',
        isSearchCollapse: false,  // 搜索栏是否折叠
        isImportCollapse: false,  // 导入栏是否折叠
        loading: false,
        is: '',
        expandRows: [], // 已经展开的rows
        currentRow: ''  // 当前行数据
      }
    },
    components: {
      SelectTree,
      PartDeviceNodeForm
    },
    activated () {
    },
    mounted () {
      this.refreshList()
    },
    watch: {
      'searchForm.runState': {
        handler (newVal, oldVal) {
            console.log(newVal)
        },
        immediate: true // 第一次绑定数据时就触发
        }
      },
    methods: {
      /**
       * @param {Object} row
       * @param {Object} expanded 布尔值，expanded===true表示展开，expanded===false表示折叠
       */
      expandChange (row, expanded) {
        this.$nextTick(function () {
          this.accordion(row) // 手风琴显示，不管是展开还是折叠，重置懒加载状态，包括自身的，
          if (expanded) {
            this.expandRows.push(row) // 将当前行放入已展开行
          }
        })
      },
      /**
       * 判断candicateRow是不是row的祖先节点
       * @param {Object} candicateRow
       * @param {Object} row
       */
      isAncestor (candicateRow, row) {
        let parents = row.parentIds.split(",")
        if (parents.indexOf(candicateRow.id) !== -1) {
          return true
        }
        return false
      },
      /**
       * 手风琴方式，并且关闭的节点再次点击，重置为懒加载状态
       * @param {Object} row 当前行
       */
      accordion (row) {
        for (let i = this.expandRows.length - 1; i >= 0; i--) { // 逆序删除，解决删除节点后序号乱序的问题
          if (!this.isAncestor(this.expandRows[i], row)) { // 关闭所有非当前节点父节点的节点，实现手风琴
            this.resetLoadState(this.expandRows[i].id) // 重置懒加载状态
            this.expandRows.splice(i, 1) // 数组截断
          }
        }
      },
      /**
       * 重置懒加载状态
       * @param {Object} rowKey
       */
      resetLoadState (rowKey) {
        this.$set(this.$refs.treeTable.store.states.lazyTreeNodeMap, rowKey, [])
        this.$set(this.$refs.treeTable.store.states.treeData[rowKey], 'loading', false)
        this.$set(this.$refs.treeTable.store.states.treeData[rowKey], 'loaded', false)
        this.$set(this.$refs.treeTable.store.states.treeData[rowKey], 'expanded', false)
      },
      // 树懒加载
      loadNode (row, treeNode, resolve) {
        this.reSolve = resolve
        if (treeNode.level < 4) {
          this.$http({
            url: '/basicdata/basictree/partDeviceNode/nextLevelTreeData',
            method: 'get',
            params: {
              id: row.id
            }
          }).then(({data}) => {
            if (row.runState === '0') {
                for (let count in data.data) {
                  data.data[count].runState = '0'
                }
            }
            if (row.isShow === '0') {
                for (let count in data.data) {
                  data.data[count].isShow = '0'
                }
            }
            resolve(data.data)
            this.$set(this.$refs.treeTable.store.states.treeData[row.id], 'loading', false)
            this.$set(this.$refs.treeTable.store.states.treeData[row.id], 'loaded', true)
          })
        }
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.dataList = []
        this.expandRows = []
        this.$http({
          url: '/basicdata/basictree/partDeviceNode/nextLevelTreeData',
          method: 'get',
          params: {
          }
        }).then(({data}) => {
          this.dataList = data.data
          this.loading = false
        })
      },
      /**
       * 重置父节点懒加载，并展开
       * @param {Object} row 当前行
       */
      refreshCurrentNode () {
        this.resetLoadState(this.currentRow.id)  // 重置当前节点懒加载状态
        this.$refs.treeTable.store.loadOrToggle(this.currentRow) // 刷新
      },
      /**
       * 重置父节点懒加载，并展开
       * @param {Object} row 当前行
       */
      refreshParentNode (row) {
        this.resetLoadState(row.parent.id)  // 重置父节点懒加载状态
        this.$refs.treeTable.store.loadOrToggle(row.parent) // 展开父节点，由于本身是懒加载，变相就是刷新
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
        // 新增下级
      addChild (id, name, level, code, row) {
        if (row.level !== '5') {
          this.$refs.partDeviceNodeForm.init('addChild', {id: '', parent: {id: id, name: name, level: level, code: code}})
          this.currentRow = row
        }
      },
       // 新增
      add () {
        this.$refs.partDeviceNodeForm.init('add', {id: '', parent: {id: '', name: ''}})
      },
      // 修改
      edit (id, row) {
        this.currentRow = row
        this.$refs.partDeviceNodeForm.init('edit', {id: id, parent: {id: '', name: ''}})
      },
      // 查看
      view (id) {
        this.$refs.partDeviceNodeForm.init('view', {id: id, parent: {id: '', name: ''}})
      },
      // 删除
      del (id, row) {
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: '/basicdata/basictree/partDeviceNode/delete',
            method: 'delete',
            params: {'id': id}
          }).then(({data}) => {
            if (data && data.success) {
              this.$message.success('删除设备节点成功: [' + row.code + ']' + row.name)
              if (row.parent.id !== '0') {  // 非根节点
                // this.refreshParentNode(row)
              } else {  // 根节点
                this.refreshList()  // 刷新整个列表
              }
            }
          })
        })
      }
    }
  }
</script>
